/*
 * Title: WADS
 * Description: Web-based Auto flow Documents System
 * Copyright: 2007
 * Company: CoE
 * @author: Mr.Nattasan Wang-Aphisit
 * @version 1.1
 */

package wads.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Vector;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import wads.com.AutoDocumentTransaction;
import wads.com.WADTools;

public class HtmlToTextServlet extends HttpServlet {
  private static final long serialVersionUID = -8109878794127069354L;
  
  private static final String CONTENT_TYPE = WADTools.SERVLET_CONTENT_TYPE;
  /**Initialize global variables*/
  private HttpSession session;
  private String app_Path;

  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }

  /**Process the HTTP Get request*/
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    session = request.getSession(false);
    app_Path = WADTools.APP_PATH;
    String currentUser = (String)session.getAttribute("UserName");

    String Filename = request.getParameter("filename");

    try{
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream(app_Path+"res/docs/InProgressAutoDoc/" + currentUser + "/" + Filename));
      AutoDocumentTransaction adt = (AutoDocumentTransaction)ois.readObject();
      String template_ID = adt.getTemplate_ID();

      ChangeHtmlToText test = new ChangeHtmlToText(template_ID, adt, currentUser);
      Vector vector = test.getVector();
      String_Write_or_Print swr = new String_Write_or_Print();
      String text;

      ServletOutputStream sos = response.getOutputStream();

      byte[] buf = new byte[1024];

      for(int i = 0 ; i < vector.size() ; i++){
        swr = (String_Write_or_Print)vector.elementAt(i);
        text = swr.text;
        if(swr.write_or_print == false){ //write
          buf = text.getBytes();
          sos.write(buf, 0, text.length());
        }else
          sos.println(text);
      }

      sos.close();
      ois.close();
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }

  /**Clean up resources*/
  public void destroy() {
  }
}